package com.example.cadmin.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.cadmin.entity.FileLog;
import com.example.cadmin.mapper.FileLogMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cadmin.utils.ResponseModel;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzsoft
 * @since 2023-01-09
 */
@Service
public class FileLogService extends ServiceImpl<FileLogMapper, FileLog> {

    @Resource
    public FileLogMapper fileLogMapper;

    /**
     * 档案操作管理list接口
     *
     * @param page
     * @param limit
     */
    public Map<String, Object> fileLogList(int page, int limit, String startDate, String endDate, String userName,
                                           HttpServletRequest request) {
        String number = Convert.toStr(request.getSession().getAttribute("number"));
        IPage<Map<String, Object>> fileLogPage = new Page<>(page, limit);//参数一是当前页，参数二是每页个数
        QueryWrapper<FileLog> fileLogQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(startDate) && StrUtil.isNotEmpty(endDate)) {
            // 时间偏于一天
            Date date = DateUtil.parse(endDate, "yyyy-MM-dd");
            Date newDate = DateUtil.offset(date, DateField.DAY_OF_MONTH, 1);
            String formatDate = DateUtil.formatDate(newDate);
            fileLogQueryWrapper.ge("createTime", startDate).le("createTime", formatDate);
        }
        if (StrUtil.isNotEmpty(userName)) {
            fileLogQueryWrapper.like("userName", userName);
        }
        fileLogQueryWrapper.eq("status", 1);
        fileLogQueryWrapper.orderByDesc("createTime");
        fileLogQueryWrapper.eq("number", number);
        fileLogPage = fileLogMapper.selectMapsPage(fileLogPage, fileLogQueryWrapper);
        Map<String, Object> resMap = new HashMap<>();
        resMap.put("code", 0);
        resMap.put("msg", "数据请求成功");
        resMap.put("data", fileLogPage.getRecords());
        resMap.put("count", fileLogPage.getTotal());
        return resMap;
    }

    /**
     * 清空日志
     */
    public ResponseModel clearLog() {
        UpdateWrapper<FileLog> fileLogUpdateWrapper = new UpdateWrapper<>();
        fileLogUpdateWrapper.set("status", 0);
        fileLogMapper.update(null, fileLogUpdateWrapper);
        return ResponseModel.success("日志已清空");
    }

}
